package com.ls.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ls.entity.Customer;
import com.ls.entity.OrderRecord;
import com.ls.entity.RuleTemplate;
import com.ls.entity.SmsRule;
import com.ls.enums.CallTypeEnum;
import com.ls.service.ICustomerService;
import com.ls.service.IOrderRecordService;
import com.ls.service.IRuleTemplateService;
import com.ls.service.ISmsRuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

import static com.ls.constant.SystemConstants.*;

/**
 * 清除短信轮询
 */
@Slf4j
@Component
public class ClearSmsTask {
    @Autowired
    private IOrderRecordService orderRecordService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private ISmsRuleService smsRuleService;
    @Autowired
    private IRuleTemplateService ruleTemplateService;

    @Scheduled(cron = "${schedule.clear.cron}")
    public void clearSmsTask() {
        // 查询需要处理的用户
        List<Customer> customersList = customerService.list(new LambdaQueryWrapper<Customer>()
                .gt(Customer::getCurrentQuantity, NUMBER_0)
                .eq(Customer::getValidFlag, VALID_TRUE)
        );
        if (customersList == null || customersList.size() == 0 || customersList.isEmpty()) {
            return;
        }
        customersList.forEach(customer -> {

            LocalDateTime clearTime = customer.getMemberClearTime();
            LocalDateTime expireTime = customer.getMemberExpireTime();
            LocalDateTime smsClearTime = customer.getSmsClearTime();
            LocalDateTime smsExpireTime = customer.getSmsExpireTime();
            //清除过期会员订单
            if (getIsEqualTime(clearTime,null)) {
                OrderRecord memberOrderRecord = orderRecordService.getOne(
                        new LambdaQueryWrapper<OrderRecord>()
                                .eq(OrderRecord::getCustomerId, customer.getCustomerId())
                                .eq(OrderRecord::getSmsType, SMS_PACKAGE_STATUS_TRUE)
                                .in(OrderRecord::getOrderStatus, Arrays.asList(PAY_STATUS_SUCCESS, PAY_STATUS_FREE))
                                .eq(OrderRecord::getProductType, PRODUCT_TYPE_MEMBER)
                                .orderByAsc(OrderRecord::getOrderRecordId)
                                .last("LIMIT 1")
                );
                if (memberOrderRecord != null) {
                    memberOrderRecord.setSmsType(SMS_PACKAGE_STATUS_FALSE);
                    orderRecordService.updateById(memberOrderRecord);
                }
            }
            //清除过期短信订单
            if (getIsEqualTime(smsClearTime,null)) {
                OrderRecord memberOrderRecord = orderRecordService.getOne(
                        new LambdaQueryWrapper<OrderRecord>()
                                .eq(OrderRecord::getCustomerId, customer.getCustomerId())
                                .eq(OrderRecord::getSmsType, SMS_PACKAGE_STATUS_TRUE)
                                .in(OrderRecord::getOrderStatus, Arrays.asList(PAY_STATUS_SUCCESS, PAY_STATUS_FREE))
                                .eq(OrderRecord::getProductType, PRODUCT_TYPE_SMS)
                                .orderByAsc(OrderRecord::getOrderRecordId)
                                .last("LIMIT 1")
                );
                if (memberOrderRecord != null){
                    memberOrderRecord.setSmsType(SMS_PACKAGE_STATUS_FALSE);
                    orderRecordService.updateById(memberOrderRecord);
                }
            }
            //会员过期clearTime != null && expireTime != null && clearTime.isBefore(LocalDateTime.now()) && expireTime.isBefore(LocalDateTime.now()) && customer.getMemberStatus() == MEMBER_STATUS_TRUE
            if (clearTime != null && expireTime != null && getIsEqualTime(clearTime,expireTime) && customer.getMemberStatus() == MEMBER_STATUS_TRUE) {
                IntStream.rangeClosed(1, 5).forEach(i -> {
                    // 按呼叫类型分组处理规则
                    List<SmsRule> smsRuleList = smsRuleService.list(new LambdaQueryWrapper<SmsRule>()
                            .eq(SmsRule::getCustomerId, customer.getCustomerId())
                            .eq(SmsRule::getCallType, i)
                            .orderByDesc(SmsRule::getUpdateTime)
                    );

                    AtomicInteger counter = new AtomicInteger(0);
                    smsRuleList.forEach(smsRule -> {
                        CallTypeEnum callTypeEnum = CallTypeEnum.getRoleEnum(smsRule.getCallType());

                        // 处理非会员规则：停用除第一个有效规则外的所有规则
                        boolean shouldDisable = counter.getAndIncrement() > 0
                                || CallTypeEnum.IN_NOT_DISTURB.equals(callTypeEnum);

                        if (shouldDisable) {
                            smsRule.setValidFlag(VALID_FALSE);
                            smsRuleService.updateById(smsRule);
                        }

                        // 保留最新模板逻辑
                        List<RuleTemplate> ruleTemplateList = ruleTemplateService.list(
                                new LambdaQueryWrapper<RuleTemplate>()
                                        .eq(RuleTemplate::getRuleId, smsRule.getRuleId())
                                        .orderByDesc(RuleTemplate::getCreateTime)
                        );

                        if (ruleTemplateList.size() > 1) {
                            RuleTemplate latestTemplate = ruleTemplateList.get(0);
                            ruleTemplateService.remove(new LambdaQueryWrapper<RuleTemplate>()
                                    .eq(RuleTemplate::getRuleId, smsRule.getRuleId())
                                    .ne(RuleTemplate::getId, latestTemplate.getId())
                            );
                        }
                    });
                });

                customer.setCurrentQuantity(customer.getSmsThaliNumTotal());
                customer.setSmsTotal(customer.getSmsThaliNum());
                customer.setMessageNumTotal(NUMBER_0);
                customer.setMessageNum(NUMBER_0);
                customer.setMemberStatus(MEMBER_STATUS_EXPIRE);
//                customer.setMemberExpireTime(null);
                customer.setMemberClearTime(null);
                customer.setRoleId((long) ROLE_NOMEMBER);
                //会员未过期，短信过期
            } else if (clearTime != null && expireTime != null && getIsEqualTime(clearTime,null) && !getIsEqualTime(clearTime,expireTime) && customer.getMemberStatus() == MEMBER_STATUS_TRUE) {
                OrderRecord memberOrderRecord = orderRecordService.getOne(
                        new LambdaQueryWrapper<OrderRecord>()
                                .eq(OrderRecord::getCustomerId, customer.getCustomerId())
                                .eq(OrderRecord::getSmsType, SMS_PACKAGE_STATUS_DEFAULT)
                                .in(OrderRecord::getOrderStatus, Arrays.asList(PAY_STATUS_SUCCESS, PAY_STATUS_FREE))
                                .eq(OrderRecord::getProductType, PRODUCT_TYPE_MEMBER)
                                .orderByAsc(OrderRecord::getOrderRecordId)
                                .last("LIMIT 1")
                );
                memberOrderRecord.setSmsType(SMS_PACKAGE_STATUS_TRUE);
                orderRecordService.updateById(memberOrderRecord);
                customer.setCurrentQuantity(customer.getSmsThaliNumTotal() + memberOrderRecord.getMonthSmsQuantity());
                customer.setSmsTotal(customer.getSmsThaliNum() + memberOrderRecord.getMonthSmsQuantity());
                customer.setMessageNumTotal(memberOrderRecord.getMonthSmsQuantity());
                customer.setMessageNum(memberOrderRecord.getMonthSmsQuantity());
                customer.setMemberClearTime(customer.getMemberClearTime().plusMonths(memberOrderRecord.getPeriod()));
            }
            if (smsClearTime != null && smsExpireTime != null && getIsEqualTime(smsClearTime,null) && getIsEqualTime(smsClearTime,smsExpireTime)) {
                customer.setCurrentQuantity(customer.getMessageNumTotal());
                customer.setSmsTotal(customer.getMessageNum());
                customer.setSmsThaliNumTotal(NUMBER_0);
                customer.setSmsThaliNum(NUMBER_0);
                customer.setSmsExpireTime(null);
                customer.setSmsClearTime(null);
            } else if (smsClearTime != null && smsExpireTime != null && getIsEqualTime(smsClearTime,null) && !getIsEqualTime(smsClearTime,smsExpireTime)) {
                OrderRecord memberOrderRecord = orderRecordService.getOne(
                        new LambdaQueryWrapper<OrderRecord>()
                                .eq(OrderRecord::getCustomerId, customer.getCustomerId())
                                .eq(OrderRecord::getSmsType, SMS_PACKAGE_STATUS_DEFAULT)
                                .in(OrderRecord::getOrderStatus, Arrays.asList(PAY_STATUS_SUCCESS, PAY_STATUS_FREE))
                                .eq(OrderRecord::getProductType, PRODUCT_TYPE_SMS)
                                .orderByAsc(OrderRecord::getOrderRecordId)
                                .last("LIMIT 1")
                );
                memberOrderRecord.setSmsType(SMS_PACKAGE_STATUS_TRUE);
                orderRecordService.updateById(memberOrderRecord);
                customer.setCurrentQuantity(customer.getMessageNumTotal() + memberOrderRecord.getMonthSmsQuantity());
                customer.setSmsTotal(customer.getMessageNum() + memberOrderRecord.getMonthSmsQuantity());
                customer.setSmsThaliNumTotal(memberOrderRecord.getMonthSmsQuantity());
                customer.setSmsThaliNum(memberOrderRecord.getMonthSmsQuantity());
                customer.setSmsClearTime(customer.getSmsClearTime().plusMonths(memberOrderRecord.getPeriod()));
            }
            LambdaUpdateWrapper<Customer> updateWrapper = new LambdaUpdateWrapper<Customer>()
                    .set(Customer::getCurrentQuantity, customer.getCurrentQuantity())
                    .set(Customer::getSmsTotal, customer.getSmsTotal())
                    .set(Customer::getMessageNumTotal, customer.getMessageNumTotal())
                    .set(Customer::getMessageNum, customer.getMessageNum())
                    .set(Customer::getSmsThaliNumTotal, customer.getSmsThaliNumTotal())
                    .set(Customer::getSmsThaliNum, customer.getSmsThaliNum())
                    .set(Customer::getMemberExpireTime, customer.getMemberExpireTime())
                    .set(Customer::getMemberClearTime, customer.getMemberClearTime())
                    .set(Customer::getSmsExpireTime, customer.getSmsExpireTime())
                    .set(Customer::getSmsClearTime, customer.getSmsClearTime())
                    .set(Customer::getMemberStatus, customer.getMemberStatus())
                    .set(Customer::getRoleId, customer.getRoleId())
                    .eq(Customer::getCustomerId, customer.getCustomerId());
            customerService.update(updateWrapper);
        });
    }
    public Boolean getIsEqualTime(LocalDateTime time,LocalDateTime time1){
        // 1. 处理 time 为 null 的情况
        if (time == null) {
            return false;
        }
        // 2. 计算 time 加一天的日期
        LocalDate targetDate = time.plusDays(1).toLocalDate();

        // 3. 根据 time1 是否为 null 决定比较逻辑
        if (time1 == null) {
            // 情况1：比较 time+1天 是否等于今天
            LocalDate today = LocalDate.now();
            return targetDate.equals(today);
        } else {
            // 情况2：比较 time+1天 是否等于 time1+1天
            LocalDate targetDate2 = time1.plusDays(1).toLocalDate();
            LocalDate today = LocalDate.now();
            return targetDate.equals(targetDate2)&&targetDate.equals(today);
        }
    }
}
